// Copyright 2022 marcello<volibearw@gmail.com>. All rights reserved.

package main

// generateModelToProtoPart 生成 fromProto 部分
func generateModelToProtoPart(param *CLIParam, tableName string, columns []Columns) string {
	var funcStr = ""
	if !param.Proto {
		// 如果没有打开生成proto, proto字段名不一致的情况出现
		// 就不生成此方法
		return funcStr
	}
	funcStr += "// ToProto model 转 protobuf \n"

	if len(columns) == 0 {
		// 表里没有字段,返回空函数
		funcStr += "func (" + getFirstWordToLowercase(tableName) + " *" + toCamelString(tableName) + ") ToProto()"
		funcStr += " pb." + toCamelString(tableName) + " {\n"
		funcStr += "    return pb." + toCamelString(tableName) + " {\n"
		funcStr += "    }\n"
		funcStr += "}\n\n"
		return funcStr
	}

	funcStr += "func (" + columns[0].TableNameFirstWordLowercase + " *" + columns[0].TableNameCame + ") ToProto()"
	funcStr += " *pb." + columns[0].TableNameCame + " {\n"
	funcStr += "    return &pb." + columns[0].TableNameCame + " {\n"

	var (
		parseStr  = "" // 额外处理part
		fieldLine = ""
	)

	// from proto 字段组装
	for _, column := range columns {
		// 特殊处理ID部分
		var (
			a = column.TableNameFirstWordLowercase + "." + column.ColumnNameCame
		)

		if param.ModelUseGorm && param.ModelIncludeGormModel {
			// gorm中id字段要使用ID
			if isGormDefaultModelIDField(column.ColumnName) {
				a = "uint32(" + column.TableNameFirstWordLowercase + ".ID)"
			}

			// 特殊处理gorm中 CreatedAt, UpdatedAt, DeletedAt
			if isGormDefaultModelTimeField(column.ColumnName) {
				a = column.TableNameFirstWordLowercase + "." + column.ColumnNameCame +
					".Format(\"2006-01-02 15:04:05\")"
			}

			if isGormDefaultModelDeletedField(column.ColumnName) {
				continue
			}
		}

		if isDatetime(column) {
			a = column.TableNameFirstWordLowercase + "." + column.ColumnNameCame +
				".Format(\"2006-01-02 15:04:05\")"
		}

		if isDate(column) {
			a = column.TableNameFirstWordLowercase + "." + column.ColumnNameCame +
				".Format(\"2006-01-02\")"
		}

		fieldLine += "        " + column.ColumnNameCame + ":" + a + ",\n"
	}
	funcStr += parseStr
	funcStr += fieldLine
	funcStr += "    }\n"
	funcStr += "}\n\n"
	return funcStr
}
